using System;
using System.Collections.Generic;
using System.Text;

namespace Kotonoha.Server.Search {
    public class Normalizer {
        private Expression root = new Expression("", null);

        public string replace(string other) {
            int i = 0;
            StringBuilder b = new StringBuilder(other.Length);
            while (i < other.Length) {
                string val = root.find(other, i);
                b.Append(val);
                i += val.Length;
            }
            return b.ToString();
        }
    }

    public class Expression {
        private Dictionary<string, Expression> inner = new Dictionary<string, Expression>();
        private string letter;
        private string replacement;

        public Expression(string letter, string replacement) {
            this.letter = letter;
            this.replacement = replacement;
        }

        public string find(string s, int i) {
            if (i >= s.Length) {
                throw new IndexOutOfRangeException(string.Format("String `{0}` couldn't be parsed, got stuck on {1}", s,
                                                                 letter));
            }
            string idx;
            idx = s.Substring(i, char.IsSurrogatePair(s, i) ? 2 : 1);
            Expression val;
            if (inner.TryGetValue(idx, out val)) {
                return val.find(s, i + idx.Length);
            }
            return replacement;
        }
    }
}